package cn.wolfcode.p2p.business.service.impl;

import cn.wolfcode.p2p.Exception.ErrorCode;
import cn.wolfcode.p2p.base.query.QueryObject;
import cn.wolfcode.p2p.business.domain.PlatformBankInfo;
import cn.wolfcode.p2p.business.mapper.PlatformBankInfoMapper;
import cn.wolfcode.p2p.business.service.IPlatformBankInfoService;
import cn.wolfcode.p2p.util.AssertUtil;
import cn.wolfcode.p2p.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PlatformBankInfoServiceImpl implements IPlatformBankInfoService {

    @Autowired
    private PlatformBankInfoMapper platformBankInfoMapper;

    @Override
    public List<PlatformBankInfo> listPlatformBankInfo() {
        return platformBankInfoMapper.selectAll();
    }

    @Override
    public PageResult queryForPage(QueryObject qo) {
        int count = platformBankInfoMapper.queryForCount(qo);
        if (count == 0) {
            return PageResult.empty(qo.getPageSize());
        }
        int totalPage = count % qo.getPageSize() == 0 ? count / qo.getPageSize() : count / qo.getPageSize() + 1;
        if(totalPage < qo.getCurrentPage()){
            qo.setCurrentPage(totalPage);
        }
        List<PlatformBankInfo> listData = platformBankInfoMapper.queryForList(qo);
        return new PageResult(listData,count,qo.getCurrentPage(),qo.getPageSize());

    }

    @Override
    public void saveOrUpdate(PlatformBankInfo platformBankInfo) {
        if (platformBankInfo.getId() == null) {
            AssertUtil.instance().isFalse(platformBankInfoMapper.selectByAccountNumber(platformBankInfo.getAccountNumber()) == 1, ErrorCode.THE_ACCOUNT_ALREADY_EXISTS);
            platformBankInfoMapper.insert(platformBankInfo);
        }else{
            platformBankInfoMapper.updateByPrimaryKey(platformBankInfo);
        }
    }
}
